﻿#region Licence
// <copyright file="SampleModule/CreateOrUpdateAppelViewModel.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>26/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System.Collections.Generic;
using System.Linq;
using Database.POCO;
using GalaSoft.MvvmLight.CommandWpf;
using Helpers;
using Helpers.Class;
using Interfaces.Enums;
using SampleModule.Class;

#endregion

namespace SampleModule.ViewModels
{
    public class CreateOrUpdateAppelViewModel : ViewModelBaseModule
    {
        #region properties

        private SampleAppel _appel;
        public SampleAppel Appel
        {
            get { return _appel; }
            set
            {
                _appel = value;
                RaisePropertyChanged(() => Appel);
            }
        }

        private List<DestinatairesAppels> _destinataires;
        public List<DestinatairesAppels> Destinataires
        {
            get { return _destinataires; }
            set
            {
                _destinataires = value;
                RaisePropertyChanged(() => Destinataires);
            }
        }

        private string _newComment;
        public string NewComment
        {
            get { return _newComment; }
            set
            {
                _newComment = value;
                RaisePropertyChanged(() => NewComment);
                SaveCommentCommand.RaiseCanExecuteChanged();
            }
        }

        private List<SampleAppelCommentaires> _commentsAppel;
        public List<SampleAppelCommentaires> CommentsAppel
        {
            get { return _commentsAppel; }
            set
            {
                _commentsAppel = value;
                RaisePropertyChanged(() => CommentsAppel);
            }
        }

        public RelayCommand SaveCommand { get; set; }
        public RelayCommand CancelCommand { get; set; }
        public RelayCommand SaveCommentCommand { get; set; }
        #endregion

        public CreateOrUpdateAppelViewModel(SampleAppel appel)
        {
            SaveCommand = new RelayCommand(Save, CanSave);
            CancelCommand = new RelayCommand(Cancel, CanCancel);
            SaveCommentCommand = new RelayCommand(SaveComment);

            if (appel.ID == 0)
            {
                appel.DateHeure = DateTimeHelper.Now;
                appel.UserOrigine = Services.AccessControlService.CurrentUser;
                Services.LoggerService.LogMonitoring("Nouvel Appel");
            }
            else
            {
                MarkedAsRead(appel);
            }
            Appel = appel;
            OnLoad();
        }

        public CreateOrUpdateAppelViewModel(long idAppel)
        {
            SaveCommand = new RelayCommand(Save, CanSave);
            CancelCommand = new RelayCommand(Cancel, CanCancel);
            SaveCommentCommand = new RelayCommand(SaveComment);

            var appel = Services.DatabaseService.Service.GetById<SampleAppel>(idAppel);
            if (appel != null)
            {
                if (appel.ID == 0)
                {
                    appel.DateHeure = DateTimeHelper.Now;
                    appel.UserOrigine = Services.AccessControlService.CurrentUser;
                }
                else
                {
                    MarkedAsRead(appel);
                }
                Appel = appel;
            }
            OnLoad();
        }

        #region relaycommand

        private void SaveComment()
        {
            var comment = new SampleAppelCommentaires
                          {
                              Appel = Appel,
                              Commentaire = NewComment,
                              UserCreateComment = Services.AccessControlService.CurrentUser
                          };
            Services.DatabaseService.Service.Save<SampleAppelCommentaires>(comment);
            LoadComments();

            //Enregistrement d'une notification pour annoncer un nouveau commentaire
            //Enregistrement des notifications
            var destinataires = Destinataires.Where(d => d.IsSelected).ToList();
            if (destinataires.Any())
            {
                //On ajoute l'utilisateur à l'origine du commentaire
                if (!destinataires.Any(d => d.Utilisateur.ID == Appel.UserOrigine.ID))
                {
                    destinataires.Add(new DestinatairesAppels{Utilisateur = Appel.UserOrigine});    
                }

                foreach (var destinataire in destinataires)
                {
                    if (destinataire != null && destinataire.Utilisateur != Services.AccessControlService.CurrentUser)
                    {
                        //Enregistrement d'une notification utilisateur
                        var resume = comment.Commentaire.Length > 50
                            ? comment.Commentaire.Substring(0, 50)
                            : comment.Commentaire;
                        var sujet = Appel.Sujet.Length > 15 ? Appel.Sujet.Substring(0, 15) : Appel.Sujet;
                        Services.NotificationService.SaveNotificationUser(
                            string.Format(Services.LocalizedService.LocalizedFromKey("CreateAppel_NewCommentNotification"), sujet),
                            string.Format("{0}...", resume), ValueNotificationEnum.ToOpen, Appel.ID,
                            destinataire.Utilisateur, TypeModulesEnum.Appels);
                    }
                }
            }
        }

        private bool CanCancel()
        {
            return Services.NavigationService.CanGoBack();
        }

        private void Cancel()
        {
            Close();
        }

        private bool CanSave()
        {
            ValueRightsEnum rights;
            if (Services.AccessControlService.IsAuthorizedFunction(Services.RightsService.GetIdentifiantRight((int)RightsEnum.Appel, TypeModulesEnum.Appels), out rights))
            {
                return rights.HasFlag(ValueRightsEnum.Modification);
            }
            return false;
        }

        private void Save()
        {
            //Sauvegarde des destinataires associés si il y a
            var dest = Destinataires.Where(d => d.IsSelected);
            if (dest.Any())
            {
                Services.DatabaseService.Service.Delete<SampleAppelUtilisateurs>(a => a.Appel.ID == Appel.ID);
                foreach (var destinataire in dest)
                {
                    var appelDest = new SampleAppelUtilisateurs {Appel = Appel, Destinataire = destinataire.Utilisateur};
                    Services.DatabaseService.Service.Save<SampleAppelUtilisateurs>(appelDest);
                }
            }

            var logActionI18N = Appel.ID != 0
                ? Services.LocalizedService.LocalizedFromKey("Generic_Modification")
                : Services.LocalizedService.LocalizedFromKey("Generic_Ajout");
            var logMessage = string.Format(Services.LocalizedService.LocalizedFromKey("CreateAppel_LogSystemSaveMessage"), logActionI18N,
                Appel.ID);
            var logAction = Appel.ID != 0 ? ValueNotificationEnum.Add : ValueNotificationEnum.Modification;

            //Enregistrement de l'appel
            Services.DatabaseService.Service.Save<SampleAppel>(Appel, true, logMessage, logAction);

            //Enregistrement des notifications
            if (dest.Any())
            {
                foreach (var destinataire in dest)
                {
                    //Enregistrement d'une notification utilisateur
                    var resume = string.Empty;
                    if (!string.IsNullOrEmpty(Appel.Message))
                    {
                        resume = Appel.Message.Length > 50 ? Appel.Message.Substring(0, 50) : Appel.Message;    
                    }
                    Services.NotificationService.SaveNotificationUser(Appel.Sujet, string.Format("{0}...", resume), ValueNotificationEnum.ToOpen, Appel.ID, destinataire.Utilisateur, TypeModulesEnum.Appels);
                }
            }

            Close();
        }

        #endregion

        public void OnLoad()
        {
            var utilisateurs = Services.DatabaseService.Service.GetAll<SysUtilisateur>();
            Destinataires = new List<DestinatairesAppels>();
            foreach (var utilisateur in utilisateurs)
            {
                Destinataires.Add(new DestinatairesAppels { Utilisateur = utilisateur});
            }
            SelectDestinataires();
            LoadComments();
        }

        #region private

        private void LoadComments()
        {
            CommentsAppel = Appel.Commentaires != null ? Appel.Commentaires.ToList() : new List<SampleAppelCommentaires>();
        }

        /// <summary>
        /// Permet de sélectionner les destinataires déja présents dans l'appel
        /// </summary>
        private void SelectDestinataires()
        {
            if (Appel != null)
            {
                var destinataires = Services.DatabaseService.Service.Where<SampleAppelUtilisateurs>(a => a.Appel.ID == Appel.ID);
                if (destinataires.Any())
                {
                    foreach (var personne in destinataires)
                    {
                        if (personne.Destinataire != null)
                        {
                            SampleAppelUtilisateurs personne1 = personne;
                            var dest = Destinataires.Where(d => d.Utilisateur.ID == personne1.Destinataire.ID);
                            if (dest.Any())
                            {
                                dest.First().IsSelected = true;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Fermeture du controle
        /// </summary>
        private void Close()
        {
            if (Services.NavigationService.GetTypeViewModelToBack() == typeof(AccueilAppelsViewModel))
            {
                Services.NavigationService.GoBack("LoadDatas", new object[] { });    
            }
            else
            {
                Services.NavigationService.GoBack();
            }
        }

        /// <summary>
        /// Regarde si il faut marquer l'appel comme lu pour l'utilisateur courant
        /// </summary>
        /// <param name="appel"></param>
        private void MarkedAsRead(SampleAppel appel)
        {
            if (appel != null && appel.ID != 0)
            {
                //On regarde si l'utilisateur courant est destinataire de cet appel
                var appelsDest =
                    Services.DatabaseService.Service.Where<SampleAppelUtilisateurs>(
                        a => a.Appel.ID == appel.ID && a.Destinataire.ID == Services.AccessControlService.CurrentUser.ID);
                if (appelsDest.Any())
                {
                    var appelDest = appelsDest.First();
                    appelDest.IsView = true;
                    Services.DatabaseService.Service.Save<SampleAppelUtilisateurs>(appelDest);
                }
            }
        }
        #endregion
    }
}
